# -*- coding: utf-8 -*-

from odoo import models, fields, api
from odoo.exceptions import ValidationError


class Department(models.Model):
    """部门模型 - 模仿若依部门管理"""
    _name = 'device.department'
    _description = '部门管理'
    _order = 'sequence, name'
    _parent_name = "parent_id"
    _parent_store = True
    _rec_name = 'complete_name'
    
    name = fields.Char('部门名称', required=True)
    complete_name = fields.Char('完整名称', compute='_compute_complete_name', recursive=True, store=True)
    code = fields.Char('部门编码', required=True)
    
    # 父子关系
    parent_id = fields.Many2one('device.department', '上级部门', ondelete='cascade')
    parent_path = fields.Char(index=True)
    child_ids = fields.One2many('device.department', 'parent_id', '下级部门')
    
    # 负责人
    leader_id = fields.Many2one('res.users', '负责人')
    device_leader_id = fields.Many2one('device.user', 'Device负责人')
    phone = fields.Char('联系电话')
    email = fields.Char('邮箱')
    
    # 基础信息
    sequence = fields.Integer('排序', default=10)
    status = fields.Boolean('部门状态', default=True)
    
    # 创建和修改信息
    create_time = fields.Datetime('创建时间', default=fields.Datetime.now)
    update_time = fields.Datetime('更新时间', default=fields.Datetime.now)
    create_by = fields.Many2one('res.users', '创建者', default=lambda self: self.env.user)
    update_by = fields.Many2one('res.users', '更新者', default=lambda self: self.env.user)
    
    # 统计字段
    user_count = fields.Integer('用户数量', compute='_compute_user_count')
    
    @api.depends('name', 'parent_id.complete_name')
    def _compute_complete_name(self):
        for dept in self:
            if dept.parent_id:
                dept.complete_name = f"{dept.parent_id.complete_name} / {dept.name}"
            else:
                dept.complete_name = dept.name
    
    @api.depends('child_ids')
    def _compute_user_count(self):
        for dept in self:
            # 计算本部门及所有子部门的用户数量
            all_dept_ids = dept.get_children_departments().ids + [dept.id]
            dept.user_count = self.env['res.users'].search_count([
                ('department_id', 'in', all_dept_ids)
            ])
    
    @api.constrains('code')
    def _check_code_unique(self):
        for record in self:
            if self.search_count([('code', '=', record.code), ('id', '!=', record.id)]) > 0:
                raise ValidationError(f'部门编码 {record.code} 已存在，请使用其他编码。')
    
    @api.constrains('parent_id')
    def _check_parent_id(self):
        if not self._check_recursion():
            raise ValidationError('不能创建循环的部门层级关系。')
    
    def write(self, vals):
        vals['update_time'] = fields.Datetime.now()
        vals['update_by'] = self.env.user.id
        return super().write(vals)
    
    def get_children_departments(self):
        """获取所有子部门"""
        return self.search([('parent_path', '=like', self.parent_path + '%')])
    
    def get_parent_departments(self):
        """获取所有父部门"""
        if not self.parent_path:
            return self.env['device.department']
        
        parent_ids = [int(x) for x in self.parent_path.split('/') if x and x != str(self.id)]
        return self.browse(parent_ids)
